using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sensor.UI.Processors;


public class DataMessageProcessor : IDisposable
{
    private BlockingCollection<string>? _queue;
    // 优化：调整批处理大小以提高低延迟性能
    private const int MaxBatchSize = 100;
    private const int MaxDataMessageSize = 1024 * 10;
    private readonly StringBuilder _stringBuilder = new();
    private CancellationTokenSource? _cancellationTokenSource;
    private Task? _processorTask;
    private bool _disposedValue;

    // 支持异步处理的回调（推荐），若需保持同步可保留Action
    public Func<string, CancellationToken, Task>? OnProcessAsync { get; set; }


    /// <summary>
    /// 添加数据到队列
    /// </summary>
    public void Add(string data)
    {
        if (_cancellationTokenSource == null)
        {
            return;
        }

        try
        {
            // 优化：使用短超时时间避免在高并发下长时间阻塞
            _queue?.TryAdd(data, 100, _cancellationTokenSource.Token);
        }
        catch (AggregateException ex)
        {
            // 过滤取消异常（正常流程）
            ex.Handle(e => e is OperationCanceledException);
        }
    }


    /// <summary>
    /// 启动数据处理任务
    /// </summary>
    public void Start()
    {
        // 确保前一个任务已停止
        Stop();
        _stringBuilder.Clear();
        // 优化：增加队列容量以减少阻塞
        _queue = new BlockingCollection<string>(50000);
        _cancellationTokenSource = new CancellationTokenSource();
        var cancellationToken = _cancellationTokenSource.Token;

        _processorTask = Task.Factory.StartNew(async () =>
        {
            await ProcessQueueAsync(cancellationToken).ConfigureAwait(false);

        }, TaskCreationOptions.LongRunning);


    }


    /// <summary>
    /// 停止数据处理任务
    /// </summary>
    public void Stop()
    {
        try
        {
            // 取消令牌并等待任务结束
            _cancellationTokenSource?.Cancel();
            if (_processorTask != null && !_processorTask.IsCompleted)
            {
                // 最多等待1秒，避免无限阻塞
                _processorTask.Wait(TimeSpan.FromMilliseconds(100));
            }
        }
        catch (AggregateException ex)
        {
            // 过滤取消异常（正常流程）
            ex.Handle(e => e is OperationCanceledException);
        }
        finally
        {
            // 释放资源
            _processorTask?.Dispose();
            _processorTask = null;
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = null;

            // 先标记“不再添加元素”，阻止生产者继续添加
            if (_queue != null)
            {
                _queue.CompleteAdding();
                // 优化：减少清理循环的超时时间以提高停止效率
                while (_queue.TryTake(out _, TimeSpan.FromMilliseconds(10)))
                {
                    // 快速清理队列中的剩余元素
                }
            }
        }
    }


    /// <summary>
    /// 异步处理队列数据
    /// </summary>
    private async Task ProcessQueueAsync(CancellationToken cancellationToken)
    {
        if (_queue == null)
        {
            return;
        }

        while (!cancellationToken.IsCancellationRequested)
        {
            try
            {
                if (_stringBuilder.Length > MaxDataMessageSize)
                {
                    _stringBuilder.Clear();
                    _stringBuilder.AppendLine("数据清空");
                }
                
                // 优化：缓存队列计数，避免重复计算
                var queueCount = _queue.Count;
                var count = Math.Min(MaxBatchSize, queueCount);
                
                if (count > 0)
                {
                    // 优化：使用预先计算的count值，避免在循环中重复计算
                    for (int i = 0; i < count; i++)
                    {
                        _stringBuilder.AppendLine(_queue.Take(cancellationToken));
                    }

                    if (OnProcessAsync != null)
                    {
                        await OnProcessAsync(_stringBuilder.ToString(), cancellationToken).ConfigureAwait(false);
                    }
                    // 优化：减少延迟时间以提高响应性
                    await Task.Delay(1, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    // 优化：减少空闲时的延迟时间以提高响应性
                    await Task.Delay(10, cancellationToken).ConfigureAwait(false);
                }

            }
            catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
            {
                // 正常取消，退出循环
                break;
            }
        }
    }


    #region IDisposable实现
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposedValue)
        {
            if (disposing)
            {
                // 释放托管资源
                Stop();
            }

            _disposedValue = true;
        }
    }

    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }
    #endregion
}